﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using WinAutomator.Library;

namespace WinAutomator.Plugin
{
    public class MoveThumb : Thumb
    {
        public MoveThumb()
        {
            DragDelta += new DragDeltaEventHandler(this.MoveThumb_DragDelta);
        }

        private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            Control item = this.DataContext as Control;
            
            if (item != null)
            {
                PluginViewModel p = (PluginViewModel)item.DataContext;

                double left = p.Left;
                double top = p.Top;

                p.Left = left + e.HorizontalChange;
                p.Top = top + e.VerticalChange;

                foreach (WAConnector tb in FindVisualChildren<WAConnector>(item))
                {
                    Point relativePoint = tb.TransformToAncestor(item).Transform(new Point(0, 0));

                    Point pt = new Point(p.Left + relativePoint.X + (tb.Width / 2), p.Top + +relativePoint.Y + (tb.Width / 2));
                    tb.AnchorPoint = pt;
                    ((WAConnectorViewModel)tb.DataContext).AnchorPoint = pt;
                }

            }
        }

        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
    }
}
